package top.infopub.mgr.sys.web;


import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import top.infopub.generic.GenericController;
import top.infopub.mgr.common.cnst.Constants;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.hr.domain.StaffOfficeDomain;
import top.infopub.mgr.hr.service.DeptInfoService;
import top.infopub.mgr.hr.service.OrgInfoService;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.hr.service.StaffOfficeService;
import top.infopub.mgr.sys.domain.OperatorDomain;
import top.infopub.mgr.sys.service.OperatorService;
import top.infopub.mgr.sys.service.RoleService;
import top.infopub.mgr.sys.vo.OperatorVo;
import top.infopub.model.hr.DeptInfo;
import top.infopub.model.hr.OrgInfo;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.sys.Operator;
import top.infopub.model.sys.Role;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.MD5;
import top.infopub.util.ObjectUtils;
import top.infopub.util.StringHelper;

import com.github.pagehelper.Page;
import com.google.common.collect.Maps;


/**
 * 系统用户管理
 * @author Awoke
 * @version 2018年10月15日
 * @see OperatorController
 * @since
 */
@Controller
@RequestMapping("/operator")
public class OperatorController extends GenericController {

    @Autowired
    private OperatorService operatorService;

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private OrgInfoService orgInfoService;

    @Autowired
    private DeptInfoService deptInfoService;

    @Autowired
    private StaffOfficeService staffOfficeService;

    @Autowired
    private StaffInfoService staffInfoService;

    /**
     * 用户管理列表
     * @return
     */
    @RequestMapping("/list")
    public String list(HttpServletRequest request) {
        // 查询所有可用的公司
        Map<String, Object> queryMap = Maps.newHashMap();
        queryMap.put("orderCondition", " types asc ");
        queryMap.put("state", "1");
        List<OrgInfo> orgInfos = orgInfoService.selectByMapWhere(queryMap);
        request.setAttribute("orgInfos", orgInfos);
        return "/sys/layoprator-list";
    }

    /**
     * 根据公司查找所有部门
     * @param request
     * @return
     */
    @RequestMapping("/getAllDeptByOrgId")
    @ResponseBody
    public Map<String, Object> getAllDeptByOrgId(String orgId) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<DeptInfo> deptInfos = deptInfoService.selectAllByOrgId(orgId);
            map.put("depts", deptInfos);
        }
        catch (Exception e) {
            log.error("", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 根据部门查询人员
     * @param request
     * @return
     */
    @RequestMapping("/getValidStaffByDept")
    @ResponseBody
    public Map<String, Object> getValidStaffByDept(String deptId) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<StaffOfficeDomain> staffs = staffOfficeService.selectValidStaffByDept(deptId);
            map.put("staffs", staffs);
        }
        catch (Exception e) {
            log.error("", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 查询人员信息
     * @param request
     * @return
     */
    @RequestMapping("/getStaffInfoById")
    @ResponseBody
    public Map<String, Object> getStaffInfoById(String staffId) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(staffId);
            map.put("staffInfo", staffInfo);
        }
        catch (Exception e) {
            log.error("", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 根据用户ID获取用户
     * @param id
     * @return
     */
    @RequestMapping("/getOperatorById")
    public @ResponseBody RspVo<Operator> getOperatorById(String id) {
        Operator operator = operatorService.selectByPrimaryKey(id);
        if (operator == null) {
            operator = new Operator();
        }
        return RspVo.getSuccessResponse(operator);
    }

    /**
     * 用户管理列表数据
     * @return
     */
    @RequestMapping("/queryData")
    @ResponseBody
    public RspVo<OperatorDomain> queryData(OperatorVo operatorVo, ParamPage paramPage) {
        Page<OperatorDomain> page = new Page<OperatorDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        if (StringUtils.isNotBlank(operatorVo.getSjpName())) {
            operatorVo.setSjpName(operatorVo.getSjpName().toUpperCase());
        }
        if (StringUtils.isNotBlank(operatorVo.getSpyName())) {
            operatorVo.setSpyName(operatorVo.getSpyName().toUpperCase());
        }
        operatorVo.setBisDelete(0);
        page = operatorService.selectPageByDomainWhere(page, operatorVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());

    }

    /**
     * 用户管理列表数据（审批流程-分配审批人使用）
     * @return
     */
    @RequestMapping("/queryDataByConditon")
    @ResponseBody
    public RspVo<OperatorDomain> queryDataByConditon(OperatorVo operatorVo, ParamPage paramPage) {
        Page<OperatorDomain> page = new Page<OperatorDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        if (StringUtils.isNotBlank(operatorVo.getSjpName())) {
            operatorVo.setSjpName(operatorVo.getSjpName().toUpperCase());
        }
        if (StringUtils.isNotBlank(operatorVo.getSpyName())) {
            operatorVo.setSpyName(operatorVo.getSpyName().toUpperCase());
        }
        operatorVo.setBisDelete(0);
        page = operatorService.selectPageByDomainWhere(page, operatorVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    @RequestMapping("/save")
    @SuppressWarnings("unchecked")
    public @ResponseBody RspVo<Operator> save(OperatorVo operatorVo) {
        // 执行新增
        if (StringUtils.isBlank(operatorVo.getId())) {
            if (!operatorVo.getSpassword().equals(operatorVo.getSpassword1())) {
                return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo(Constants.CHANGE_PWD_NEWS_NOT_EQUALS);
            }
            // 判断用户名是否存在
            if (operatorService.isUsernameExist(operatorVo.getSuserName())) {
                return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("用户名已经存在~");
            }
            // 查询人员信息 
            StaffInfo staff = staffInfoService.selectByPrimaryKey(operatorVo.getHrStaffId());
            String realName = staff.getStaffName();
            String mobile = staff.getPhone();

            Operator operator = new Operator();
            ObjectUtils.copyObjValue(operatorVo, operator);
            operator.setSoperatorNo(codeGeneratorConfigService.generatorCode("sys_operator"));
            operator.setDaddDate(new Date());
            operator.setSaddOperator(SessionUserUtils.getSessionUserId());
            operator.setBisAdmin(0);
            operator.setBisFreeze(1);
            operator.setSrealName(realName);
            operator.setSmobile(mobile);
            operator.setHrStaffId(operatorVo.getHrStaffId());
            operator.setSpyName(StringHelper.getFullSpell(operator.getSrealName()));
            operator.setSjpName(StringHelper.getFirstSpell(operator.getSrealName()));
            // MD加盐
            operator.setSpassword(MD5.salt(operator.getSuserName(), operator.getSpassword()));
            operator.setBisDelete(0);
            operatorService.insert(operator);
            return RspVo.getSuccessResponse(operator);
        }
        else {// 执行修改
            /* Operator operator = operatorService.selectByPrimaryKey(operatorVo.getId());
             ObjectUtils.copyObjValue(operatorVo, operator);
             operator.setBisFreeze(operatorVo.getBisFreeze());
             operator.setHrStaffId(operatorVo.getHrStaffId());
             operator.setDmodifyDate(new Date());
             operator.setSmodifyOperator(SessionUserUtils.getSessionUserId());
             operator.setSpyName(StringHelper.getFullSpell(operator.getSrealName()));
             operator.setSjpName(StringHelper.getFirstSpell(operator.getSrealName()));
             operator.setSpassword(null);
             operatorService.updateBySelective(operator);
             return RspVo.getSuccessResponse(operator);*/
            return RspVo.getSuccessResponse();
        }
    }

    /**
     * 修改用户启用/停用状态
     * @return 
     * @see
     */
    @RequestMapping("/updateStatus")
    public @ResponseBody RspVo<String> updateStatus(String id) {
        Operator opt = operatorService.selectByPrimaryKey(id);
        Integer oldStatus = opt.getBisFreeze();
        Integer newStatus = 0;
        if (oldStatus == 0) {
            newStatus = 1;
        }
        else {
            newStatus = 0;
        }
        opt.setDmodifyDate(new Date());
        opt.setSmodifyOperator(SessionUserUtils.getSessionUserId());
        opt.setBisFreeze(newStatus);
        operatorService.updateByPrimaryKey(opt);
        return RspVo.getSuccessResponse();
    }

    /**
     * 修改用户密码
     * @param checkboxId
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/change-password")
    public @ResponseBody RspVo<String> changePwd(String cid, String pasword, String pasword1) {
        if (StringUtils.isEmpty(cid) || StringUtils.isEmpty(pasword)
            || StringUtils.isEmpty(pasword1)) {
            return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo(Constants.BAD_PARAMETERS_REQUEST);
        }
        if (!pasword.equals(pasword1)) {
            return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo(Constants.CHANGE_PWD_NEWS_NOT_EQUALS);
        }
        Operator operator = operatorService.selectByPrimaryKey(cid);
        operator.setDmodifyDate(new Date());
        operator.setSmodifyOperator(SessionUserUtils.getSessionUserId());
        // MD加盐
        operator.setSpassword(MD5.salt(operator.getSuserName(), pasword));
        operatorService.updateBySelective(operator);
        return RspVo.getSuccessResponse();
    }

    /**
     * 删除用户
     * @param checkboxId
     * @return
     * @throws Exception
     */
    @RequestMapping("/delete")
    public @ResponseBody RspVo<String> delete(String[] checkboxId) {
        operatorService.delete(checkboxId);
        return RspVo.getSuccessResponse();
    }

    /**
     * 查询所有角色
     * @param id
     * @return
     */
    @RequestMapping("/getAllRoleAndCheckRole")
    public @ResponseBody RspVo<Map<String, Object>> getAllRoleAndCheckRole(String id) {
        Map<String, Object> resMap = new HashMap<String, Object>();
        //查询所有角色
        List<Role> roles = roleService.selectAll();
        //查询用户已有角色
        List<Role> checkroles = roleService.selectByUserId(id);
        resMap.put("allRole", roles);
        resMap.put("checkRole", checkroles);
        return RspVo.getSuccessResponse(resMap);
    }

    /**
     * 查询用户已有的角色
     * @param id
     * @return
     */
    @RequestMapping("/getOperatorCheckRole")
    public @ResponseBody RspVo<Role> getOperatorCheckRole(String id) {
        List<Role> roles = roleService.selectByUserId(id);
        return RspVo.getSuccessResponse(roles.size(), roles);
    }

    /**
     * 查询用户没有的角色
     * @param id
     * @return
     */
    @RequestMapping("/getOperatorNotCheckRole")
    public @ResponseBody RspVo<Role> getOperatorNotCheckRole(String id) {
        List<Role> roles = roleService.selectOperatorNoCheckRole(id);
        return RspVo.getSuccessResponse(roles.size(), roles);
    }

    /**
     * 给用户分配角色
     * @param checkRoleId 选中的角色集合
     * @param operatorId 用户ID
     * @return
     */
    @RequestMapping("/saveOperatorRole")
    public @ResponseBody RspVo<String> saveOperatorRole(String rid, String roleIds) {
        /*if (StringUtils.isBlank(rid) || StringUtils.isBlank(roleIds)) {
            return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo(Constants.BAD_PARAMETERS_REQUEST);
        }*/
        operatorService.saveOperatorRole(roleIds, rid);
        return RspVo.getSuccessResponse();
    }

}
